<template>
    <div ref="test" style="background-color: #1ba1e2">
      <div class="back">
        <gcanvas ref="gcanvess" class="gcanvasStyle"></gcanvas>
      </div>
        <!-- <image class="image" src="https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1542875348&di=09cb95a938f88d5d6db695891db693d2&imgtype=jpg&er=1&src=http%3A%2F%2Fi0.hdslb.com%2Fbfs%2Farchive%2F7434d2f3a9ebfe58903917372b9227469e7f3904.png" ></image> -->
        <!-- <gcanvas @touchstart="touchstart" @touchmove="touchmove" @touchend="touchend" ref="gcanvess"
                style="width: 650px;height: 1000px;position:absolute;left:0;top:0"></gcanvas>
        <div class="button" @click="mosaic(canvasObj)"></div> -->
        <!--  @click="mosaic" -->

    </div>
</template>
<style type="text/css" scoped>
.button {
  position: absolute;
  left: 100px;
  bottom: 50px;
  width: 300px;
  height: 200px;
  background-color: #131c35;
}
.image {
  width:510px;
  height: 300px;

}
.back {
  background-color: #131c35;
}
.gcanvasStyle {
  width: 750px;
  height: 1000px;
  background-color: black;
}
</style>
<script>
var libGCanvas = require("weex-gcanvas");
var imageEnv = require("weex-gcanvas/gcanvasimage.js");
var lastTime = 0;
const data = [
  {
    name: "芳华",
    percent: 0.4,
    a: "1"
  },
  {
    name: "妖猫传",
    percent: 0.2,
    a: "1"
  },
  {
    name: "机器之血",
    percent: 0.18,
    a: "1"
  },
  {
    name: "心理罪",
    percent: 0.15,
    a: "1"
  },
  {
    name: "寻梦环游记",
    percent: 0.05,
    a: "1"
  },
  {
    name: "其他",
    percent: 0.12,
    a: "1"
  }
];

var smoothTrail = function(c, cw, ch){
  
/*=============================================================================*/	
/* Initialize
/*=============================================================================*/
  this.init = function(){
    this.loop();
  };		
  
  /*=============================================================================*/	
  /* Variables
/*=============================================================================*/
  var _this = this;
  this.c = c;
  this.ctx = c.getContext('2d');
  this.cw = cw;
  this.ch = ch;
  this.mx = 0;
  this.my = 0;
  
  //trail
  this.trail = [];
  this.maxTrail = 200;
  this.mouseDown = false;
  
  this.ctx.lineWidth = .1;
  this.ctx.lineJoin = 'round';
  
  this.radius = 1;
  this.speed = 0.4;
  this.angle = 0;
  this.arcx = 0;
  this.arcy = 0;
  this.growRadius = true;
  this.seconds = 0;
  this.milliseconds = 0;
  
  /*=============================================================================*/	
  /* Utility Functions
/*=============================================================================*/				
  this.rand = function(rMi, rMa){return ~~((Math.random()*(rMa-rMi+1))+rMi);};
  this.hitTest = function(x1, y1, w1, h1, x2, y2, w2, h2){return !(x1 + w1 < x2 || x2 + w2 < x1 || y1 + h1 < y2 || y2 + h2 < y1);};
  
  /*=============================================================================*/	
  /* Create Point
/*=============================================================================*/
  this.createPoint = function(x, y){					
    this.trail.push({
      x: x,
      y: y						
    });
  };
  
  /*=============================================================================*/	
  /* Update Trail
/*=============================================================================*/
  this.updateTrail = function(){					
    
    if(this.trail.length < this.maxTrail){
      this.createPoint(this.arcx, this.arcy);
    }					
    
    if(this.trail.length >= this.maxTrail){
      this.trail.splice(0, 1);
    }					
  };
  
  /*=============================================================================*/	
  /* Update Arc
/*=============================================================================*/
  this.updateArc = function(){
    this.arcx = (this.cw/2) + Math.sin(this.angle) * this.radius;
    this.arcy = (this.ch/2) + Math.cos(this.angle) * this.radius;					
    var d = new Date();
    this.seconds = d.getSeconds();
    this.milliseconds = d.getMilliseconds();
    this.angle += this.speed*(this.seconds+1+(this.milliseconds/1000));
    
    if(this.radius <= 1){
      this.growRadius = true;
    } 
    if(this.radius >= 200){
      this.growRadius = false;
    }
    
    if(this.growRadius){
      this.radius += 1;	
    } else {
      this.radius -= 1;	
    }
  };
  
  /*=============================================================================*/	
  /* Render Trail
/*=============================================================================*/
  this.renderTrail = function(){
    var i = this.trail.length;					
    
    this.ctx.beginPath();
    while(i--){
      var point = this.trail[i];
      var nextPoint = (i == this.trail.length) ? this.trail[i+1] : this.trail[i];
      
      var c = (point.x + nextPoint.x) / 2;
      var d = (point.y + nextPoint.y) / 2;						
      this.ctx.quadraticCurveTo(Math.round(this.arcx), Math.round(this.arcy), c, d);
      
      
      
    };
    this.ctx.strokeStyle = 'rgba('+this.rand(200,255)+','+this.rand(0, 150)+','+this.rand(100, 255)+', 1)';	
    this.ctx.stroke();
    this.ctx.closePath();
    
  };			
 
  
  /*=============================================================================*/	
  /* Clear Canvas
/*=============================================================================*/
  this.clearCanvas = function(){
    //this.ctx.globalCompositeOperation = 'source-over';
    //this.ctx.clearRect(0,0,this.cw,this.ch);
    
    this.ctx.globalCompositeOperation = 'destination-out';
    this.ctx.fillStyle = 'rgba(0,0,0,1)';
    this.ctx.fillRect(0,0,this.cw,this.ch);					
    this.ctx.globalCompositeOperation = 'lighter';
  };
  
  /*=============================================================================*/	
  /* Animation Loop
/*=============================================================================*/
  this.loop = function(){
    var loopIt = function(){
      var id = requestAnimationFrame(loopIt, _this.c);
      _this.clearCanvas();
      _this.updateArc();
      _this.updateTrail();
      _this.renderTrail();							
    };
    loopIt();					
  };
  
};

function requestAnimationFrame(callback,element){
  var currTime = new Date().getTime();
  var timeToCall = Math.max(0,16 - (currTime - lastTime));
  var id = setTimeout(function(){callback(currTime + timeToCall);}, timeToCall);
  lastTime = currTime + timeToCall;
  return id;
};

function drawLoading(ctx){
  var cw = 400,
      ch = 300,
      rand = function(a,b){return ~~((Math.random()*(b-a+1))+a);},
      dToR = function(degress){
        return degress * (Math.PI / 180);
      },
      circle = {
        x: (cw / 2) + 5,
        y: (ch / 2) + 22,
        radius: 90,
        speed: 2,
        rotation: 0,
        angleStart: 270,
        angleEnd: 90,
        hue: 220,
        thickness: 18,
        blur: 25
      },
      particles = [],
      particleMax = 100,
      updateCircle = function(){
        if (circle.rotation < 360) {
          circle.rotation += circle.speed;
        } else {
          circle.rotation = 0;
        }
      },
      renderCircle = function(){
        ctx.save();
        ctx.translate(circle.x,circle.y);
        ctx.rotate(dToR(circle.rotation));
        ctx.beginPath();
        ctx.arc(0,0,circle.radius,dToR(circle.angleStart),dToR(circle.angleEnd),true);
        ctx.lineWidth = circle.thickness;
        ctx.strokeStyle = gradient1;
        ctx.stroke();
        ctx.restore();
      },
      renderCircleBorder = function(){
        ctx.save();
        ctx.translate(circle.x,circle.y);
        ctx.rotate(dToR(circle.rotation));
        ctx.beginPath();
        ctx.arc(0,0,circle.radius + (circle.thickness/2),dToR(circle.angleStart),dToR(circle.angleEnd),true);
        ctx.lineWidth = 2;
        ctx.strokeStyle = gradient2;
        ctx.stroke();
        ctx.restore();
      },
      renderCircleFlare = function(){
        ctx.save();
        ctx.translate(circle.x,circle.y);
        ctx.rotate(dToR(circle.rotation+185));
        ctx.scale(1,1);
        ctx.beginPath();
        ctx.arc(0,circle.radius,30,0,Math.PI*2,false);
        ctx.closePath();
        var gradient3 = ctx.createRadialGradient(0,circle.radius,0,0,circle.radius,30);
        gradient3.addColorStop(0,'rgba(192, 64, 128,0.35)');
        gradient3.addColorStop(1,'rgba(192, 64, 128,0)');
        ctx.fillStyle = gradient3;
        ctx.fill();
        ctx.restore();
      },
      renderCircleFlare2 = function(){
        ctx.save();
        ctx.translate(circle.x,circle.y);
        ctx.rotate(dToR(circle.rotation+165));
        ctx.scale(1.5,1);
        ctx.beginPath();
        ctx.arc(0,circle.radius,25,0,Math.PI*2,false);
        ctx.closePath();
        var gradient4 = ctx.createRadialGradient(0,circle.radius,0,0,circle.radius,25);
        gradient4.addColorStop(0,'rgba(255, 128, 0,0.2)');
        gradient4.addColorStop(1,'rgba(255, 128, 0,0)');
        ctx.fillStyle = gradient4;
        ctx.fill();
        ctx.restore();
      },
      createParticles = function(){
        if (particles.length < particleMax) {
          particles.push({
            x: (circle.x + circle.radius * Math.cos(dToR(circle.rotation-85))) + (rand(0,circle.thickness*2) - circle.thickness),
            y: (circle.y + circle.radius * Math.sin(dToR(circle.rotation-85))) + (rand(0,circle.thickness*2) - circle.thickness),
            vx: (rand(0,100)-50)/1000,
            vy: (rand(0,100)-50)/1000,
            radius: rand(1,6)/2,
            alpha: rand(10,20)/100
          });
        }
      },
      updateParticles = function(){
        var i = particles.length;
        while (i--) {
          var p = particles[i];
          p.vx += (rand(0,100)-50)/750;
          p.vy += (rand(0,100)-50)/750;
          p.x += p.vx;
          p.y += p.vy;
          p.alpha -= .01;

          if (p.alpha < .02) {
            particles.splice(i,1)
          }
        }
      },
      renderParticles = function(){
        var i = particles.length;
        while (i--) {
          var p = particles[i];
          ctx.beginPath();
          ctx.fillRect(p.x,p.y,p.radius,p.radius);
          ctx.closePath();
          ctx.fillStyle = 'rgba(255, 0, 0,' + p.alpha + ')';
        }
      },
      clear = function(){
        ctx.globalCompositeOperation = 'destination-out';
        ctx.fillStyle = 'rgba(0,0,0,0.1)';
        ctx.fillRect(0,0,cw,ch);
        ctx.globalCompositeOperation = 'lighter';
      },
      loop = function(){
        clear();
        updateCircle();
        renderCircle();
        renderCircleBorder();
        renderCircleFlare();
        renderCircleFlare2();
        createParticles();
        updateParticles();
        renderParticles();
      };

      ctx.lineCap = 'round';
      var gradient1 = ctx.createLinearGradient(0,-circle.radius,0,circle.radius);
      gradient1.addColorStop(0,'rgba(51, 102, 204,0.25)');
      gradient1.addColorStop(1,'rgba(51, 102, 204,0)');
      var gradient2 = ctx.createLinearGradient(0,-circle.radius,0,circle.radius);
      gradient2.addColorStop(0,'rgba(0, 85, 255,0)');
      gradient2.addColorStop(0.1,'rgba(255,255,255,0.7)');
      gradient2.addColorStop(1,'rgba(0, 85, 255,1)');

      setInterval(loop,16);
}

// 绘制图片
function drawImg(ctx, size) {
  var image = new imageEnv();
  image.src = 
    "https://timgsa.baidu.com/timg?image&quality=80&size=b9999_10000&sec=1542875348&di=09cb95a938f88d5d6db695891db693d2&imgtype=jpg&er=1&src=http%3A%2F%2Fi0.hdslb.com%2Fbfs%2Farchive%2F7434d2f3a9ebfe58903917372b9227469e7f3904.png";
  // function draw() {
    // if (image.complete) {
    //   clearInterval(i);
      // console.log('drawimage:' + image.complete);
      // ctx.drawImage(image, 100, 100, size.width, size.height);
      // ctx.render()
      
      // console.log('ctx:' + JSON.stringify(ctx));
    // }
  // }
  // var i = setInterval(draw, 16);
  setTimeout(function(){
    ctx.drawImage(image, 100, 100, size.width, size.height);
  }, 200);
}

function getXY(obj, x, y) {
  // var w = obj.width;
  // var h = obj.height;
  // var d = obj.data;
  var color = [];
  // color[0] = obj.data[4 * (y * w + x)];
  // color[1] = obj.data[4 * (y * w + x) + 1];
  // color[2] = obj.data[4 * (y * w + x) + 2];
  // color[3] = obj.data[4 * (y * w + x) + 3];
  color[0] = "189";
  color[1] = "163";
  color[2] = "123";
  color[3] = "1";
  return color;
}

function setXY(obj, x, y, color) {
  var w = obj.width;
  var h = obj.height;
  var d = obj.data;
  obj.data[4 * (y * w + x)] = color[0];
  obj.data[4 * (y * w + x) + 1] = color[1];
  obj.data[4 * (y * w + x) + 2] = color[2];
  obj.data[4 * (y * w + x) + 3] = color[3];
}

module.exports = {
  data: {
    startX: 0,
    startY: 0,
    currentX: 0,
    currentY: 0,
    context: {},
    imageContext: {},
    canvasObj: {},
    width: 510,
    height: 300
  },
  methods: {
    mosaic(ref) {
      var ctx = ref.getContext("2d");
      var Oimg = ctx.getImageData(200, 200, 50, 30);
      // console.log('Oimg:' + JSON.stringify(Oimg));
      var width = 510;
      var height = 300;
      var newImg = ctx.createImageData(510, 300);
      // console.log('newImg:' + JSON.stringify(newImg));
      var num = 1;
      var stepW = width / num;
      var stepH = height / num;
      for (let i = 0; i < stepH; i++) {
        for (let j = 0; j < stepW; j++) {
          var color = getXY(
            Oimg,
            j * num + Math.floor(Math.random() * num),
            i * num + Math.floor(Math.random() * num)
          );
          for (var k = 0; k < num; k++) {
            for (var l = 0; l < num; l++) {
              //设置小方格的颜色
              setXY(newImg, j * num + l, i * num + k, color);
            }
          }
        }
      }
      // console.log('newImg:' + JSON.stringify(newImg));
      ctx.putImageData(newImg,0,0);
      
    },
    touchstart(event) {
      this.startX = event.changedTouches[0].pageX;
      this.startY = event.changedTouches[0].pageY;
      this.context.strokeStyle = "#17acf6"; //设置线的颜色状态
      this.context.lineWidth = 10; //设置线宽状态
    },
    touchmove(event) {
      this.currentX = event.changedTouches[0].pageX;
      this.currentY = event.changedTouches[0].pageY; //进行绘制
      this.context.moveTo(this.startX, this.startY);
      this.context.lineTo(this.currentX, this.currentY);
      this.context.stroke();
      this.startX = event.changedTouches[0].pageX;
      this.startY = event.changedTouches[0].pageY;
    },
    touchend(event) {}
  },
  mounted: function() {
    var self = this; /*获取元素引用*/ //以下是核心代代码，需在合适的时机调用，我这里在自己定义的界面加载完成的全局事件中调用了
    var ref = self.$refs.gcanvess; /*通过元素引用获取canvas对象*/
    var size = {
      width: self.width,
      height: self.height
    };
    self.canvasObj = libGCanvas.start(ref);
    // /*获取绘图所需的上下文，目前不支持3d*/
    // self.context = self.canvasObj.getContext("2d");
    var cl = new smoothTrail(self.canvasObj,750,1000);
    cl.init();
    // 绘制loading
    // drawLoading(self.context);
    // 绘图
    // drawImg(self.context, size);
    // /*设置字体大小*/
    // self.context.font = "56px Arial"; /*在指定位置绘制文字*/
    // var color = self.context.createLinearGradient(0,0,750,100);
    // color.addColorStop(0,"#e345e8");
    // color.addColorStop(0.5,"#23fe67");
    // color.addColorStop(1,"blue");
    // self.context.fillStyle = color;
    // self.context.textAlign = "center";
    // self.context.fillText("Hello Word Hello Word", 200, 100); /*指定绘制图形的线的宽度*/
    // self.context.lineWidth = 10; /*在指定位置绘制矩形*/
    // self.context.strokeRect(200, 200, 200, 90);

    // // 创建渐变
    // var grd=self.context.createRadialGradient(250,250,50,250,250,250);
    // grd.addColorStop(0,"#e345e8");
    // grd.addColorStop(1,"#23fe67");
    // // 填充渐变
    // self.context.fillStyle=grd;
    // self.context.beginPath();
    // self.context.arc(250,250,250,0,2*Math.PI);
    // self.context.fill();
    // /*绘制三角形*/
    // self.context.beginPath();
    // self.context.moveTo(20, 20);
    // self.context.lineTo(20, 100);
    // self.context.lineTo(70, 100);
    // self.context.closePath();
    // self.context.stroke();
  }
};
</script >